package com.rowline.admin.module.util.filter;


import com.alibaba.fastjson.JSON;
import com.rowline.admin.module.util.context.RequestContext;
import com.rowline.admin.module.util.domain.Log;
import com.rowline.admin.module.util.utils.HttpRequestUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * ClassName:RequestFilter
 * Created by 245167
 * on 2017/8/9  09:32
 * description:请求过滤器
 */
public class RequestFilter implements Filter{

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Log.info("RequestFilter init()");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Log.info("RequestFilter doFilter()");

        RequestContext.currentContext().setHttpRequest((HttpServletRequest) servletRequest);
        RequestContext.currentContext().setHttpResponse((HttpServletResponse) servletResponse);

        Long t = System.currentTimeMillis();

        RequestContext requestContext = RequestContext.currentContext();
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        requestContext.setUrl(httpServletRequest.getRequestURI());
        String heads = JSON.toJSONString(HttpRequestUtil.getHeadersInfo(httpServletRequest));
        requestContext.setRequestHeader(heads);
        requestContext.setRequestIp(HttpRequestUtil.getIpAddress(httpServletRequest));
        requestContext.setRequestMethod(httpServletRequest.getMethod());
        Map<String,String> paramers = HttpRequestUtil.getParamers(httpServletRequest);
        String paramersStr = JSON.toJSONString(paramers);
        requestContext.setRequestParam(paramersStr);

        try {
            if (null != filterChain) {
                filterChain.doFilter(servletRequest, servletResponse); // 让目标资源执行，放行
            }
        } catch (Exception e) {
            Log.error(httpServletRequest.getRequestURI() +"] 处理请求出错 Exception :"
                    + e.getClass() + " ====> " + e.getMessage());
            e.printStackTrace();
        }
        String info = String.format("[%s(%s) ]请求处理时长： %d ms",
                httpServletRequest.getRequestURI(),
                paramersStr,
                System.currentTimeMillis() - t);
        Log.info(info);

        RequestContext.remove();


    }

    @Override
    public void destroy() {
        Log.info("RequestFilter destroy()");
    }
}
